﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.Windows;
using VoiceAI;
using Xiaowei.Services;

namespace Xiaowei.ViewModel
{
    public class MainWindowViewModel:ViewModelBase
    {
        public XiaoweiAI.XiaoweiAIStateEnum XiaoweiAIState => XiaoweiAI.Instance.XiaoweiAIState;
        public bool IsInitialized => XiaoweiAI.Instance.IsInitialized;
        public ObservableCollection<object> History { get; } = new ObservableCollection<object>();
        public MainWindowViewModel()
        {
            XiaoweiAI.Instance.HistoryChanged += Instance_HistoryChanged;
            XiaoweiAI.Instance.IsInitializedChanged += Instance_IsInitializedChanged;
            XiaoweiAI.Instance.XiaoweiAIStateChanged += Instance_XiaoweiAIStateChanged;
        }

        private void Instance_HistoryChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(()=> {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        History.Insert(e.NewStartingIndex, e.NewItems[0]);
                        break;
                    case NotifyCollectionChangedAction.Move:
                        History.Move(e.OldStartingIndex, e.NewStartingIndex);
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        History.RemoveAt(e.OldStartingIndex);
                        break;
                    case NotifyCollectionChangedAction.Replace:
                        History[e.NewStartingIndex] = e.NewItems[0];
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        History.Clear();
                        break;
                    default:
                        break;
                }
            });

        }

        public override void Dispose()
        {
            XiaoweiAI.Instance.IsInitializedChanged -= Instance_IsInitializedChanged;
            XiaoweiAI.Instance.XiaoweiAIStateChanged -= Instance_XiaoweiAIStateChanged;
        }
        private void Instance_XiaoweiAIStateChanged(XiaoweiAI.XiaoweiAIStateEnum obj)
        {
            UpdateValue(nameof(XiaoweiAIState));
        }
        private void Instance_IsInitializedChanged(bool obj)
        {
            UpdateValue(nameof(IsInitialized));
        }
    }
}
